import React from 'react';
import Redirect from 'umi/redirect';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import Authorized from '@/utils/Authorized';
import { getAuthority } from '@/utils/authority';
import Exception403 from '@/pages/Exception/403';

function AuthComponent({ children, location, routerData }) {
  const auth = getAuthority();
  console.log("abcabc",auth);
  const isLogin = auth && auth[0] !== 'guest';
  const getRouteAuthority = (path, routeData) => {
    let authorities;
    routeData.forEach(route => {
      // match prefix
      console.log("pathToRegexp",pathToRegexp(`${route.path}(.*)`).test(path)); // false 进入403
      if (pathToRegexp(`${route.path}(.*)`).test(path)) {
        authorities = route.authority || authorities;

        // get children authority recursively
        if (route.routes) {
          authorities = getRouteAuthority(path, route.routes) || authorities;
        }
      }
    });
    return authorities;
  };
  console.log("abcdef",location.pathname, routerData);
  console.log("abcdefgh",getRouteAuthority(location.pathname, routerData));
  console.log("abcdefg",children);
  // debugger;  此处的Authorized就是components下的Authorized.js中的Authorized 最终返回的就是CheckPermissions.js这个组件
  return <Authorized
      authority={getRouteAuthority(location.pathname, routerData)}
      // undefined ? 1:2 返回结果为 2
      noMatch={isLogin ? <Exception403 /> : <Redirect to="/user/login" />}
    >
      {/* 这个children就是要通过权限校验的子组件比如登陆成功后的页面*/}
      {children}
    </Authorized>
 ;
}
// menu 说明这个权限校验是登录成功之后的校验
export default connect(({ menu: menuModel }) => ({
  routerData: menuModel.routerData,
}))(AuthComponent);
